layui.define(['layer', 'table', 'dtree', 'form', 'jquery', 'laydate','transfer','hospital'], function (exports) {
    // noinspection SpellCheckingInspection
    var layer = layui.layer //弹层
        , table = layui.table //表格
        , $ = layui.jquery
        ,transfer = layui.transfer
        ,dtree = layui.dtree
        ,hospital = layui.hospital
        , form = layui.form;
    
    var assignmentRolesIndex;
    var userTableInfo; //用户界面 用户表格
    var employeeTableInfo; //用户界面 员工表格
    var openCount=0;//初始化dtree次数
    var hospitalSelectInfo;//用于存储医院下拉框
    var nowEditUser; //当前操作用户
    userPage = {

        initUserPage:function(){
            this.initUserTable();
            this.initTableRowListen();
            this.initTableTopToolListen();
            this.initEditUserRoleListen();
            this.listenUserTableSwitch();
            this.listenEmployeeJobSelect();
            this.listenEmployeeSearch();
        },

        /*
        * 初始化 用户页面表格
         */
         initUserTable:function(){
             //执行一个 table 实例
              userTableInfo= table.render({
                 elem: '#demo', //选取html表格的id
                 id: 'userId',
                 response: {
                     // statusName: 'status', //规定数据状态的字段名称，默认：code
                     statusCode: '200 ' //规定成功的状态码，默认：0
                     // ,msgName: 'hint' //规定状态信息的字段名称，默认：msg
                     // ,countName: 'total' //规定数据总数的字段名称，默认：count
                     // ,dataName: 'rows' //规定数据列表的字段名称，默认：data
                 }
                 ,url: '/system/user'
                 ,title: '用户表'
                 ,toolbar: '#toolTableTop'
                 ,page: true
                 ,cols: [[
                     {type: 'checkbox', fixed: 'left'}
                     ,{field: 'userName', align:'center',title: '用户名'}
                     ,{field: 'role', align:'center',title: '角色',templet: function (row){
                             if (row.roles!==undefined){
                                 var roleName = "";
                                 $.each(row.roles, function (index, val) {
                                     roleName = val.name+"," +roleName
                                 });
                                 if (roleName==="null,"){
                                     return "/";
                                 } else {

                                     return roleName=(roleName.substring(roleName.length-1)===',')?roleName.substring(0,roleName.length-1):roleName;
                                 }
                             }else {
                                 return "/";
                             }

                         }}
                     // ,{field: 'employeeName', align:'center',title: '员工',templet: function (row){
                     //        if (row.employee !=undefined){
                     //            return  row.employee.employeeName;
                     //        }
                     // }}
                     ,{field: 'status', title: '状态', align:'center' , event: 'change_status',templet: function (row){
                             var status = row.status;
                             var rowData = JSON.stringify(row);
                             switch (status) {
                                 case 0:
                                     return '<input type="checkbox" row-data=\''+ rowData + '\' name="status"  lay-skin="switch" lay-filter="user_table_Switch" lay-text="启用|禁用" >';
                                 case 1:
                                     return '<input type="checkbox" row-data=\''+ rowData + '\' name="status" checked lay-skin="switch" lay-filter="user_table_Switch" lay-text="启用|禁用" > ';
                                 default:
                                     return '<input type="checkbox" row-data=\''+ rowData + '\' name="status"    lay-skin="switch" lay-filter="user_table_Switch" lay-text="启用|禁用" >' ;
                             }
                         }}
                     ,{fixed: 'right', title: '操作',align:'center', toolbar: '#barDemo'}

                 ]]
             });
         },

        /*
        * 初始化 用户页面表格行按钮监听
       */
         initTableRowListen:function(){
             //监听行工具事件   tool是行工具条
             table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，demo 是 table 原始容器的属性 lay-filter="对应的值"
                 data = null;
                 data = obj.data;     //获得当前行数据
                 var layEvent = obj.event; //获得 lay-event 对应的值
                 if(layEvent === 'detail'){
                     nowIndex = layer.open(
                         {
                             type: 1,
                             title: '详情页面',
                             // shade: 0.8,
                             area: ['500px', '300px'],
                             btnAlign: 'c',//按钮居中对齐
                             content: $("#detail_form"), //选择表单的html Id
                             anim: 5,//弹出效果 渐显
                             success:function(index){
                                 form.val("dataForm",{
                                     "id" : data.userId, //表格赋值操作 k为表单中的name ,v为渲染表格字段
                                     "username": data.userName,
                                     "status": data.status
                                 });
                                 $("#createTime").val(data.createTime);
                                 $("#updateTime").val(data.updateTime);
                                 form.render();
                             }

                         });

                 }
                 else if(layEvent === 'del'){
                     layer.confirm('请确认是否删除用户['+ data.userName +']' , function(index){
                         var id = data.userId;
                         $.ajax({
                             type: "DELETE",
                             contentType:"application/json",//设置请求参数类型为json字符串
                             url: "/system/user/" + data.userId  ,
                             success:function(resp){
                                 var code = resp.code;
                                 if (code === 200 ){
                                     layer.close(nowIndex);
                                     layer.msg('删除成功', {icon: 1});
                                     userTableInfo.reload();
                                 }else {
                                     layer.msg("删除失败 "+resp.msg , {icon: 5});
                                 }
                             }
                         });
                         layer.close(index);
                         //向服务端发送删除指令
                     });
                 }
                 else if(layEvent === 'edit'){
                     initUserAddOrEditHtml('edit',data);
                 }
                 else if(layEvent === 'assignment_roles'){
                     assignmentRolesIndex = layer.open({
                     type: 1,
                     title: '分配角色',
                     area: ['600px', '480px'],
                     btnAlign: 'c',//按钮居中对齐
                     content: $("#add_user_roles"),
                     anim: 5,//弹出效果 渐显
                     // btn:["添加","取消"],
                     success:function(index){
                         var user_have_roles = [];
                         console.log(data);
                         $.each(data.roles, function (index, val) {
                             user_have_roles.push(val.roleId);
                         });
                         $.ajax({
                             type: "GET",
                             contentType:"application/json",//设置请求参数类型为json字符串
                             url: "/system/role" ,
                             success:function(resp){
                                 var code = resp.code;
                                 if (code === 200 ){
                                     //渲染
                                     transferData =   transfer.render({
                                         elem: '#user_role_transfer_html'  //绑定元素
                                         ,id: 'transfer_user_roles' //定义索引
                                         ,title:['全部角色名称', '用户拥有角色']
                                         ,data:resp.data
                                         ,value:user_have_roles //右侧选中的数据
                                         ,parseData: function(res){
                                             return {
                                                 "value": res.roleId //数据值
                                                 ,"title": res.name //数据标题
                                                 ,"disabled": res.disabled  //是否禁用
                                                 ,"checked": res.checked //是否选中
                                             }
                                         }

                                     });
                                 }else {
                                     layer.msg("获取参数异常 " + resp.msg, {icon: 5});
                                 }
                             }
                         });
                     }
                 });}
                 else if(layEvent === 'assignment_employee'){
                     listenEditUserEmployeeInfo(data);
                 }
             });


             table.on('tool(employee_table)', function(obj){ //注：tool 是工具条事件名，demo 是 table 原始容器的属性 lay-filter="对应的值"
                 let data = obj.data;     //获得当前行数据
                 let layEvent = obj.event; //获得 lay-event 对应的值
                 if(layEvent === 'bindRelationship'){
                     layer.confirm('请确认是否将员工['+ data.employeeName +']和账户['+ nowEditUser.userName +']关联' , function(index){
                         data.userName = nowEditUser.userName;
                         data.userId = nowEditUser.userId;
                         let initTableCondition = {where: {employeeIdView: data.employeeId}};
                         apiUpdateUserEmployeeId(data,initTableCondition);
                         layer.close(index);
                     });
                 }else {
                     layer.confirm('请确认是否解除员工['+ data.employeeName +']和账户['+ nowEditUser.userName +']关联' , function(index){
                         data.employeeId = null;
                         apiUpdateUserEmployeeId(data);
                         layer.close(index);
                     });
                 }
             });
         },

        /*
        * 初始化 用户页面表格头工具栏按钮监听
       */
        initTableTopToolListen:function () {
            //监听头工具条事件 toobar是头工具条
            table.on('toolbar(test)', function(obj){
                var checkStatus = table.checkStatus("userId") //获取选中行
                    ,data = checkStatus.data; //获取选中的数
                switch(obj.event){
                    case 'add':
                        initUserAddOrEditHtml('add',undefined);
                        break;
                    case 'batchDeleted':
                        if(data.length === 0){
                            layer.msg('请选择一行');
                        } else {
                            let keyArr = '';
                            let nameArr = '';
                            $.each(data,function (index, val) { //index是数组对象索引，val是对象
                                if (index===0){
                                    keyArr = keyArr + val.userId;
                                    nameArr = nameArr + val.userName;
                                }else {
                                    keyArr = keyArr +','+ val.userId;
                                    nameArr = nameArr + ',' + val.userName;
                                }
                            });
                            layer.confirm('是否确定删除选中的数据[' + nameArr + "]",
                                {
                                    icon:0,
                                    title: "提示",
                                    skin: "deleteTips"
                                }
                                , function(){
                                    console.log(keyArr);
                                    $.ajax({
                                        type: "POST",
                                        contentType:"application/x-www-form-urlencoded",//设置请求参数类型为json字符串
                                        url: "/system/userByBatchDelete",
                                        data:{
                                            ids: keyArr
                                        },
                                        success:function(resp){
                                            var code = resp.code;
                                            if (code === 200 ){
                                                layer.close(nowIndex);
                                                layer.msg('删除成功', {icon: 1});
                                                userTableInfo.reload();
                                            }else {
                                                layer.msg("删除失败 "+resp.msg , {icon: 5});
                                            }
                                        }
                                    });


                                });


                        }
                        break;
                }
            });
        },

        /*
        *  监听分配角色提交按钮
        */
        initEditUserRoleListen:function () {
            $("#edit_user_role").click(function () {
                // 构建jsonData
                var ddcc =  transferData.getData('transfer_user_roles');
                console.log(ddcc);
                var roleIds = '';
                $.each(ddcc, function (index, val) {
                    if (index===0){
                        roleIds = roleIds + val.value;
                    }else {
                        roleIds = roleIds +','+ val.value;
                    }
                });
                $.ajax({
                    type: "PUT",
                    contentType:"application/json",//设置请求参数类型为json字符串
                    url: "/system/user/assignRoles",
                    data: JSON.stringify({userId:data.userId ,roles:roleIds}),
                    success:function(resp){
                        var code = resp.code;
                        if (code === 200 ){
                            //上述方法等价于
                            userTableInfo.reload();
                            layer.close(assignmentRolesIndex);
                            layer.msg('修改成功', {icon: 1});

                        }else {
                            layer.msg("添加失败 " + resp.msg, {icon: 5});
                        }
                    }
                });
            });
        },

        /*
          * 监听添加、编辑框员工 职位栏 医院下拉框选择 联动部门显示
           */
        listenEmployeeJobSelect:function( ){
            let documentDeptTreeId;
            //监听医院下拉选择
            form.on( 'select(hospital_select)', function(data){
                console.log(data.elem); //得到select原始DOM对象
                console.log(data.value); //得到被选中的值
                console.log(data.othis); //得到美化后的DOM对象
                let chooseElemIndex = 'DeptDtree';
                var hId =  data.value;
                let treeData;
                $.ajax({
                    url: "/manage/department/findDeptTreeList?isCheckArr=1&&isNotChoose=yes&&hospitalId="+  hId,
                    type: "GET",
                    success: function (resp) {
                        if (resp.code === 200) {
                            treeData = resp.data;
                            //重新加载渲染
                            dtree.reload( chooseElemIndex,{
                                data:  treeData,
                            });
                        }
                    }
                });
            });
        },

        /*
        *  表格页面监听表格中的switch改变发送请求
        */
        listenUserTableSwitch: function() {
            //监听行单击事件
            form.on('switch(user_table_Switch)', function(data){
                var switch_status = data.elem.checked?1:0;
                var row_data = JSON.parse( data.elem.getAttribute('row-data'));
                $.ajax({
                    url: '/system/user/'+ row_data.userId,
                    contentType : "application/json",
                    type: 'PUT',
                    data:JSON.stringify( {status:switch_status}),
                    success: function (resp) {
                        if (resp.code===200){
                            var data = resp.data;
                            userTableInfo.reload();
                            layer.msg('保存成功', {icon: 1});
                        }else {
                            layui.form.render();
                            layer.msg("保存失败"+ " "+ resp.msg, {icon: 5});
                        }

                    }
                });

            });
        },

        /*
       *  监听 用户分配员工表格搜索提交、清除按钮
       */
        listenEmployeeSearch:function(){
            //提交搜索
            $("#searchEmployeeBtn").click(function () {
                {
                    var searchEmployee = $("#searchEmployee").val();
                    var hId = $("#hospital_select").val();
                    layui.table.reload("employee_table_Id",{
                        where:{
                            searchEmployee: searchEmployee,
                            hId: hId,
                            deptChildId: dtree.getNowParam('DeptDtree').nodeId,
                            isCheck:   $("#isBindSelect").val(),
                        }
                    })
                }
            });
            //清除搜索
            $("#clearEmployeeBtn").click(function () {
                {
                    $("#searchEmployee").val('');
                    $("#hospital_select").val('');
                    $("#isBindSelect").val('0'),
                    dtree.reload( 'DeptDtree',{
                        data:  []
                    });
                    form.render('select');
                }
            });
        }


    };


    /*
     *  初始化用户编辑或者添加框
     */
    function initUserAddOrEditHtml(type ,data) {
        var form_title = '';
        type === 'add' ? form_title = "添加用户信息" : form_title = "编辑用户信息";
        nowIndex = layer.open(  //弹出层
            {
                type: 1,
                title: form_title,
                // shade: 0.8,
                area: ['400px', '300px'],
                btnAlign: 'c',//按钮居中对齐
                content: $("#edit_form"), //选择表单的html Id
                anim: 5,//弹出效果 渐显
                btn: ['保存', '关闭'],
                yes: function (index, layero) {
                    submitAddOrEditInfo(type,data);
                    return false;
                },
                btn2: function () {
                    layer.close(nowIndex);
                },
                success:function(index){
                    if (type==='edit'){
                        $("#userName").val(data.userName);
                        let status = data.status;
                        status === 1 ? status = true :status = false;
                        $("#status").prop("checked",status);
                    }else {
                        $("#userName").val('');
                        $("#userPassword").val('');
                        $("#status").prop("checked",true);
                    }
                    layui.form.render();
                }

            });
    }

    /*
    * 提交用户编辑框 或者 添加 的信息
     */
    function submitAddOrEditInfo(type,data) {
        let request_method;
        let request_url;
        // 请求方式处理和URL处理
        if (type === 'add') {
            request_method = 'POST';
            request_url = '/system/user';
        } else {
            request_method = 'PUT';
            request_url = '/system/user/' + data.userId;
        }
        let status =  $("#status").prop("checked");
        status ? status = 1 :status =0;
        let userInfoData = {
            userName: $("#userName").val(),
            userPassword: $("#userPassword").val(),
            status: status,
            employeeId : data.employeeId==undefined?undefined:data.employeeId
        };
        $.ajax({
            type:  request_method,
            contentType:"application/json",//设置请求参数类型为json字符串
            url: request_url,
            data: JSON.stringify(userInfoData),
            success:function(resp){
                var code = resp.code;
                if (code === 200 ){
                    layer.close(nowIndex);
                    layer.msg('修改成功', {icon: 1});
                    userTableInfo.reload();
                }else {
                    layer.msg("修改失败 " + resp.msg, {icon: 5});
                }
            }
        });
    }

    /*
* 获取医院信息下拉框
*/
    function getHttpHospitalSelectInfo() {
        $.ajax({
            url:  '/manage/hospital',
            type: 'GET',
            async : false,
            success: function (resp) {
                if (resp.code === 200) {
                    hospitalSelectInfo =  resp.data;
                } else {
                    layer.msg("获取医院信息失败");
                }

            }
        });
    }

    /*
    *  监听分配用户 的员工信息
    */
    function listenEditUserEmployeeInfo(rowData){
        nowEditUser = rowData;
        let nowIndex = layer.open(
            {
                type: 1,
                title: '分配用户['+ rowData.userName + ']关联员工',
                area: ['900px', '480px'],
                btnAlign: 'c',//按钮居中对齐
                content: $("#editUserHaveEmployee"),
                anim: 5,//弹出效果 渐显
                // btn:["添加","取消"],
                success:function(index){
                    let treeData = [];
                    let documentId = '#hospital_select';
                    hospitalSelectInfo==undefined?getHttpHospitalSelectInfo():hospitalSelectInfo;
                    $(documentId).empty();
                    $(documentId).append(new Option("请选择",""));
                    $.each(hospitalSelectInfo, function (index, val) { //index是数组对象索引，val是对象
                        var hName = val.name + "(" + val.city + "/"+val.area+ ")";
                        $(documentId).append(new Option(hName,val.id));
                    });
                    if (openCount===0){
                        // 初始化树dtree renderSelect render
                        dtree.renderSelect({
                            elem: "#DeptDtree",
                            data:  treeData,
                        });
                        openCount++;
                    }else {
                        //重新加载渲染
                        dtree.reload( 'DeptDtree',{
                            data:  treeData
                        });
                    }
                    let initTableCondition;
                    if (rowData.employeeId!=undefined && rowData.employeeId!==''){
                        initTableCondition = {employeeIdView: rowData.employeeId,}
                    }else {
                        initTableCondition = {isCheck: '0'}
                    }
                    employeeTableInfo = table.render({
                        elem: '#employee_table', //选取html表格的id
                        id: 'employee_table_Id',
                        response: {statusCode: '200 ' //规定成功的状态码，默认：0
                        }
                        , url: '/manage/employee'
                        , title: '员工表'
                        , page: true
                        ,height: 'full-20' //高度最大化减去差值
                        ,cols: [[
                            {field: 'employeeNumber', title: '工号', align: 'center', sort: true, fixed: 'left'}
                            , {field: 'employeeName', title: '姓名', align: 'center', sort: true, fixed: 'left'}
                            , {field: 'employeeName', title: '信息', align: 'center', sort: true, fixed: 'left',templet: function (row){
                                 if (row.isCheck==='1'){
                                     return '[' + row.userName+ ']账户已使用';
                                 }else {
                                     return '未分配';
                                 }
                            }}
                            , {fixed: 'tool', title: '操作', width: 165, align: 'center',templet: function (row){
                                    if (row.isCheck==='1'){
                                        return '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="clearBind" >-解除绑定</a>'
                                    }else {
                                        return '<a class="layui-btn layui-btn-normal layui-btn-xs"  lay-event="bindRelationship" >+分配账号</a>'
                                    }
                            }}
                        ]]
                        ,where: initTableCondition
                    });
                    form.render('select');
                }
            });
    }

    function apiUpdateUserEmployeeId(data,initTableCondition){
        let request_method;
        let request_url;
        request_method = 'PUT';
        request_url = '/system/user/' + data.userId;
        let userInfoData = {
            userName: data.userName,
            // userPassword: data.userPassword,
            employeeId : data.employeeId
        };
        $.ajax({
            type:  request_method,
            contentType:"application/json",//设置请求参数类型为json字符串
            url: request_url,
            data: JSON.stringify(userInfoData),
            success:function(resp){
                var code = resp.code;
                if (code === 200 ){
                    layer.msg('修改成功', {icon: 1});
                    userTableInfo.reload();
                    employeeTableInfo.reload(initTableCondition);
                }else {
                    layer.msg("修改失败 " + resp.msg, {icon: 5});
                }
            }
        });
    }

    userPage.initUserPage();
    exports("user", userPage);
});